<template>
  <div class="chartsContainer">
    <div class="title">频谱展示</div>
    <!-- 配置区域 -->
    <div class="setting">
      <!-- 设备选择 -->
      <div class="label">设备选择：</div>
      <el-select
        v-model="deviceUrl"
        placeholder=""
        :multiple-limit="2"
        :multiple="true"
        collapse-tags
        @change="changeDevice"
        style="width: 180px;"
        size="mini"
        :disabled="chartType1 === 2"
      >
        <el-option
          v-for="item in deviceList"
          :key="item.deviceIp"
          :label="item.deviceName"
          :value="`${item.deviceIp}:${item.devicePort}`"
        >
        </el-option>
      </el-select>
      <div class="label">显示模式：</div>
      <el-select
        :disabled="deviceUrl.length === 1"
        size="mini"
        v-model="showCharts"
        placeholder=""
        :multiple="deviceUrl.length !== 2"
      >
        <el-option :key="1" label="频谱图" :value="1"></el-option>
        <el-option :key="2" label="瀑布图" :value="2"></el-option>
      </el-select>
    </div>
    <!-- 频谱图、瀑布图 -->
    <div class="charts">
      <div class="chart1">
        <div class="top">
          <template v-if="deviceUrl.length !== 0">
            <div class="chartTitle">
              {{ getDeviceName(0) }}
            </div>
            <!-- <el-button
              type="primary"
              size="mini"
              @click="openDialog1"
              v-if="chartType1 !== 2"
              >参数配置</el-button
            > -->
            <el-button
              type="primary"
              size="mini"
              @click="$refs.chart11.fitFlag = true"
              style="margin-right: 20px;"
              v-if="chartType1 !== 2"
              >Y轴自适应</el-button
            >
            <!-- <el-select
              style="margin-left: 5px;"
              v-model="chartType1"
              size="small"
              placeholder="请选择工作模式"
              @change="openDialog1"
            >
              <el-option label="实时模式" :value="1"></el-option>
              <el-option label="扫频模式" :value="0"></el-option>
              <el-option
                v-show="deviceUrl.length === 1"
                label="文件回放"
                :value="2"
              ></el-option>
            </el-select> -->

            <el-select
              style="margin-left: 5px;"
              v-if="chartType1 === 2"
              v-model="fileName"
              size="small"
              placeholder="请选择文件"
              @change="playbackStatus && stopPlay()"
            >
              <el-option
                v-for="item in fileList"
                :key="item"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
            <el-button
              v-if="chartType1 === 2 && playbackStatus === false"
              @click="startPlay"
              type="primary"
              size="mini"
              >开始回放</el-button
            >
            <el-button
              v-if="chartType1 === 2 && playbackStatus === true"
              type="primary"
              size="mini"
              @click="stopPlay"
              >停止回放</el-button
            >
          </template>
        </div>
        <!-- 频谱图 -->
        <PinPuChart
          :propId="'canvas1'"
          :propRef="'canvas1'"
          :url="deviceUrl"
          :chartType="chartType1"
          @showLine="showLine"
          @changePlayFlag="changePlayFlag1"
          @changeYRange="changeYRange1"
          @changeCenterFre="changeCenterFre1"
          ref="chart11"
          v-if="
            deviceUrl.length !== 2 ||
              (deviceUrl.length === 2 && showCharts === 1)
          "
        />
        <!-- 瀑布图 -->
        <PuBuChart
          :propId="'canvas2'"
          :propRef="'canvas2'"
          :url="deviceUrl"
          ref="chart12"
          v-if="
            deviceUrl.length !== 2 ||
              (deviceUrl.length === 2 && showCharts === 2)
          "
        />
      </div>
      <div class="chart1" v-if="deviceUrl.length === 2">
        <div class="top">
          <template v-if="deviceUrl.length === 2">
            <div class="chartTitle">
              {{ getDeviceName(1) }}
            </div>
            <!-- <el-button type="primary" size="mini" @click="openDialog2"
              >参数配置</el-button
            > -->
            <el-button
              type="primary"
              size="mini"
              @click="$refs.chart13.fitFlag = true"
              style="margin-right: 20px;"
              >Y轴自适应</el-button
            >
            <!-- <el-select
              v-model="chartType2"
              size="small"
              placeholder="请选择工作模式"
              @change="openDialog2"
            >
              <el-option label="实时模式" :value="1"></el-option>
              <el-option label="扫频模式" :value="0"></el-option>
            </el-select> -->
          </template>
        </div>
        <!-- 频谱图 -->
        <PinPuChart
          :propId="'canvas3'"
          :propRef="'canvas3'"
          :url="deviceUrl"
          :chartType="chartType2"
          @showLine="showLine2"
          @changePlayFlag="changePlayFlag2"
          @changeYRange="changeYRange2"
          @changeCenterFre="changeCenterFre2"
          ref="chart13"
          v-if="deviceUrl.length === 2 && showCharts === 1"
        />
        <!-- 瀑布图 -->
        <PuBuChart
          :propId="'canvas4'"
          :propRef="'canvas4'"
          :url="deviceUrl"
          ref="chart14"
          v-if="deviceUrl.length === 2 && showCharts === 2"
        />
      </div>
    </div>
    <!-- 设备一参数配置 -->
    <div v-show="false">
      <ScanSetting
        @showLine="showLine"
        ref="scanSetting1"
        @changeYRange="changeYRange1"
        :url="deviceUrl[0]"
      />
      <RealSetting
        @showLine="showLine"
        ref="realSetting1"
        @changeYRange="changeYRange1"
        :url="deviceUrl[0]"
      />
    </div>

    <!-- 设备二参数配置 -->
    <div v-show="false">
      <ScanSetting
        ref="scanSetting2"
        v-show="chartType2 === 0"
        :url="deviceUrl[1]"
      />

      <RealSetting
        @showLine="showLine2"
        ref="realSetting2"
        :url="deviceUrl[1]"
      />
    </div>

    <!-- 不需要弹窗了 -->
    <!-- 设备一参数配置弹窗 -->
    <el-dialog
      :close-on-click-modal="false"
      element-loading-background="rgba(0, 0, 0, 0.5)"
      :visible.sync="showDialog1"
      v-loading="loading1"
      width="35%"
      top="1%"
      v-if="false"
    >
      <span></span>
      <!-- 扫频模式参数配置组件 -->

      <ScanSetting
        @showLine="showLine"
        ref="scanSetting1"
        v-show="chartType1 === 0"
        @changeYRange="changeYRange1"
        :url="deviceUrl[0]"
      />

      <!-- 实时模式参数配置 -->
      <RealSetting
        @showLine="showLine"
        ref="realSetting1"
        v-show="chartType1 === 1"
        @changeYRange="changeYRange1"
        :url="deviceUrl[0]"
      />

      <span slot="footer">
        <el-button @click="showDialog1 = false">取消</el-button>
        <el-button type="primary" @click="confirm1">确认</el-button>
      </span>
    </el-dialog>

    <!-- 设备二参数配置弹窗 -->
    <el-dialog
      :close-on-click-modal="false"
      element-loading-background="rgba(0, 0, 0, 0.5)"
      title="参数配置"
      :visible.sync="showDialog2"
      v-loading="loading2"
      width="35%"
      top="1%"
      v-if="false"
    >
      <span></span>

      <!-- 扫频模式参数配置组件 -->
      <ScanSetting
        @showLine="showLine2"
        ref="scanSetting2"
        v-show="chartType2 === 0"
        :url="deviceUrl[1]"
      />

      <!-- 实时模式参数配置 -->
      <RealSetting
        @showLine="showLine2"
        ref="realSetting2"
        v-show="chartType2 === 1"
        :url="deviceUrl[1]"
      />
      <span slot="footer">
        <el-button @click="showDialog2 = false">取消</el-button>
        <el-button type="primary" @click="confirm2">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getDeviceInfo } from "@/api/tansfer.js";
import PinPuChart from "@/views/webglChart/PinPuChart.vue";
import PuBuChart from "@/views/webglChart/PuBuChart.vue";
import ScanSetting from "@/views/ChartComponents/ScanSetting.vue";
import RealSetting from "@/views/ChartComponents/RealSetting.vue";
import axios from "axios";

export default {
  name: "ChartComponents",
  data() {
    return {
      userMark: "", // 用户标识
      deviceList: [],
      deviceUrl: [],
      webSocket1: null,
      webSocket2: null,
      wsuri1: "",
      wsuri2: "",
      showCharts: [1, 2], // 默认显示频谱和瀑布图
      chartType1: "",
      chartType2: "",
      showDialog1: false,
      showDialog2: false,
      loading1: false,
      loading2: false,

      fileList: [],
      playbackStatus: false,
      fileName: "",
      playFlag1: true,
      playFlag2: true,
    };
  },
  components: {
    PinPuChart,
    PuBuChart,
    ScanSetting,
    RealSetting,
  },
  mounted() {
    // console.log(window.screen.width);
    // console.log("路由跳转信息", this.$route.query.item.anteId);
    // this.getUserMark();
    // 临时获取id为9的天线下的设备信息
    let id = this.$route.query.anteId;
    id &&
      getDeviceInfo(id)
        .then(({ data: { data } }) => {
          // console.log('频谱监视信息', data.spectrumDeviceInfoDTOList);
          this.deviceList = data.spectrumDeviceInfoDTOList;
        })
        .catch((err) => {
          console.log(err);
        });
  },
  beforeDestroy() {
    if (this.wsuri1) {
      this.webSocket1 && this.webSocket1.close();
      this.wsuri1 = "";
    }

    if (this.wsuri2) {
      this.webSocket2 && this.webSocket2.close();
      this.wsuri2 = "";
    }
  },
  provide() {
    return {
      userMark: this.userMark,
      detectType1: this.$refs.chart11 ? this.$refs.chart11.detectType : [],
    };
  },
  watch: {
    // 显示模式下拉框发生变化
    showCharts(newVal, oldVal) {
      if (newVal === 1 && oldVal === 2) {
        this.openDialog1(true);
        this.openDialog2(true);
      }
    },
  },
  methods: {
    getDeviceName(index) {
      let str;
      if (this.deviceUrl.length < index) {
        str = "";
      } else {
        this.deviceList.some((item) => {
          if (this.deviceUrl[index] === `${item.deviceIp}:${item.devicePort}`) {
            str = item.deviceName;
            return true;
          }
        });
      }
      return str;
    },
    async changeDevice(newVal) {
      // deviceUrl的长度控制着控制显示图表单选多选，所以要及时把showCharts的数据格式进行调整
      if (newVal.length !== 2) {
        this.showCharts = [1, 2];
      } else {
        this.showCharts = 1;
      }
      console.log("最新选中的设备:", newVal, newVal.length);
      // 根据最新的设备IP端口去销毁、创建最新的WebSocket链接
      if (this.wsuri1) {
        this.webSocket1.close();
        this.wsuri1 = "";
      }

      if (this.wsuri2) {
        this.webSocket2.close();
        this.wsuri2 = "";
      }

      // 初始化ws，调用接口查询设备的工作模式
      if (newVal[0]) {
        this.initWebSocket1(newVal[0]);
        try {
          const {
            data: { data },
          } = await this.getWorkMode(newVal[0]);
          // console.log('设备1工作模式:', data);
          this.chartType1 = data.workMode;
          this.openDialog1();
        } catch (error) {
          console.log(error);
        }
      }
      if (newVal[1]) {
        this.initWebSocket2(newVal[1]);
        try {
          const {
            data: { data },
          } = await this.getWorkMode(newVal[1]);
          // console.log('设备2工作模式:', data);
          this.chartType2 = data.workMode;
          this.openDialog2();
        } catch (error) {
          console.log(error);
        }
      }
    },
    // 获取用户标识
    getUserMark() {
      let temMark = sessionStorage.getItem("userMark");
      if (!temMark) {
        temMark = Date.now();
        sessionStorage.setItem("userMark", temMark);
      }
      this.userMark = temMark;
      // console.log('用户标识:', this.userMark)
    },
    initWebSocket1(url) {
      // console.log('url', url);
      this.wsuri1 = "ws://" + url + "/1_123456789";
      // this.wsuri1 = "ws://" + url + "/1_" + this.userMark;
      this.webSocket1 = new WebSocket(this.wsuri1);
      this.webSocket1.onmessage = this.webSocketOnMessage1;
      this.webSocket1.onopen = this.webSocketOnOpen1;
      this.webSocket1.onerror = this.webSocketOnError1;
      this.webSocket1.onclose = this.webSocketClose1;
    },
    webSocketOnOpen1() {
      console.log("websocket1已打开");
    },
    webSocketOnError1() {
      console.log("websocket1发生了错误");
    },
    webSocketOnMessage1(e) {
      if (!this.playFlag1) return;
      if (e.data) {
        const fileReader = new FileReader();
        fileReader.onload = () => {
          const arrayBuffer = fileReader.result; // 获取读取的 ArrayBuffer
          // 创建一个 DataView 来读取和解析 ArrayBuffer
          const dataView = new DataView(arrayBuffer);

          // 使用 DataView 的各种方法来读取数据
          // console.log('dataView', dataView)

          // 标识位
          // const int32Value = dataView.getInt32(0)
          // originStart
          const originStart = dataView.getFloat32(4);
          // originEnd
          const originEnd = dataView.getFloat32(8);
          // startFreq
          const startFreq = dataView.getFloat32(12);
          // endFreq
          const endFreq = dataView.getFloat32(16);
          // temprature
          const temprature = dataView.getFloat32(20);
          // dian
          const dian = dataView.getFloat32(24);
          // pointNum
          const pointNum = dataView.getInt32(28);
          // time
          const time = dataView.getInt32(32);
          // 数据类型
          const dataType = dataView.getInt16(36);
          // 长度
          const length = dataView.getInt16(38);
          // fFTAvg
          const fFTAvg = [];
          const fFTRealtime = [];
          const fFTMax = [];
          const fFTMin = [];
          for (let index = 40; index < 40 + 4 * length; index += 4) {
            fFTAvg.push(dataView.getFloat32(index));
            fFTRealtime.push(dataView.getFloat32(index));
          }

          switch (dataType) {
            case 3:
              for (
                let index = 40 + 4 * length;
                index < 40 + 8 * length;
                index += 4
              ) {
                fFTMax.push(dataView.getFloat32(index));
              }
              break;

            case 5:
              for (
                let index = 40 + 4 * length;
                index < 40 + 8 * length;
                index += 4
              ) {
                fFTMin.push(dataView.getFloat32(index));
              }
              break;
            case 7:
              for (
                let index = 40 + 4 * length;
                index < 40 + 8 * length;
                index += 4
              ) {
                fFTMax.push(dataView.getFloat32(index));
              }
              for (
                let index = 40 + 8 * length;
                index < 40 + 12 * length;
                index += 4
              ) {
                fFTMin.push(dataView.getFloat32(index));
              }
              break;

            default:
              break;
          }

          const data = {
            originStart,
            originEnd,
            startFreq,
            endFreq,
            temprature,
            dian,
            pointNum,
            time,
            dataType,
            length,
            fFTAvg,
            fFTRealtime,
            fFTMax,
            fFTMin,
            /* fFTMax: this.fFTMax,
            fFTMin: this.fFTMin */
          };
          // console.log('websocket接收数据:', data)
          try {
            // const data = JSON.parse(e.data)
            const chartObj = {};
            if (this.chartType1 === 1) {
              if (data.fFTRealtime) {
                // 绘制瀑布图的逻辑单独出
                chartObj.fFTRealtime = data.fFTRealtime;
              }

              if (
                this.$refs.chart11 &&
                data.fFTAvg &&
                this.$refs.chart11.detectType.includes("2")
              ) {
                chartObj.fFTAvg = data.fFTAvg;
              }
              if (
                this.$refs.chart11 &&
                data.fFTMax &&
                this.$refs.chart11.detectType.includes("3")
              ) {
                chartObj.fFTMax = data.fFTMax;
              }
              if (
                this.$refs.chart11 &&
                data.fFTMin &&
                this.$refs.chart11.detectType.includes("4")
              ) {
                chartObj.fFTMin = data.fFTMin;
              }

              if (Object.keys(chartObj).length) {
                this.$refs.chart11 &&
                  this.$refs.chart11.drawChart(
                    chartObj,
                    data.startFreq,
                    data.endFreq,
                    data.originStart,
                    data.originEnd
                  );
                this.$refs.chart12 &&
                  this.$refs.chart12.drawChart(
                    data.fFTRealtime,
                    data.startFreq,
                    data.endFreq,
                    data.originStart,
                    data.originEnd
                  );
              }

              if (data.save !== undefined) {
                this.$refs.realSetting1.saveForm.start =
                  data.save === false ? 0 : 1;
              }
            } else if (this.chartType1 === 0) {
              if (data.fFTRealtime) {
                // 绘制瀑布图的逻辑单独出
                chartObj.fFTRealtime = data.fFTRealtime;
              }

              if (
                this.$refs.chart11 &&
                data.fFTAvg &&
                this.$refs.chart11.detectType.includes("2")
              ) {
                chartObj.fFTAvg = data.fFTAvg;
              }
              if (
                this.$refs.chart11 &&
                data.fFTMax &&
                this.$refs.chart11.detectType.includes("3")
              ) {
                chartObj.fFTMax = data.fFTMax;
              }
              if (
                this.$refs.chart11 &&
                data.fFTMin &&
                this.$refs.chart11.detectType.includes("4")
              ) {
                chartObj.fFTMin = data.fFTMin;
              }

              if (Object.keys(chartObj).length) {
                this.$refs.chart11 &&
                  this.$refs.chart11.drawChart(
                    chartObj,
                    data.startFreq,
                    data.endFreq,
                    data.originStart,
                    data.originEnd
                  );
                this.$refs.chart12 &&
                  this.$refs.chart12.drawChart(
                    data.fFTRealtime,
                    data.startFreq,
                    data.endFreq,
                    data.originStart,
                    data.originEnd
                  );
              }
            } else if (this.chartType1 === 2) {
              if (data.fFTRealtime && data.fFTAvg) {
                this.$refs.chart11 &&
                  this.$refs.chart11.drawChart(
                    { fFTRealtime: data.fFTRealtime, fFTAvg: data.fFTAvg },
                    data.startFreq,
                    data.endFreq,
                    data.originStart,
                    data.originEnd
                  );
                this.$refs.chart12 &&
                  this.$refs.chart12.drawChart(
                    data.fFTRealtime,
                    data.startFreq,
                    data.endFreq,
                    data.originStart,
                    data.originEnd
                  );
              }
            }
            // 如果原始区间就小于1000，就不去做格式化数据的处理了
            if (
              this.$refs.chart11 &&
              data.originEnd - data.originStart > 1000
            ) {
              if (
                !this.$refs.chart11.disabledChange &&
                data.endFreq - data.startFreq < 1000 &&
                !this.$refs.chart11.formatStatus
              ) {
                this.$refs.chart11.formatStatus = true;
              } else if (
                data.endFreq - data.startFreq >= 1000 &&
                this.$refs.chart11.formatStatus
              ) {
                this.$refs.chart11.formatStatus = false;
              }
            }
          } catch (error) {
            console.log(error);
          }
        };
        fileReader.readAsArrayBuffer(e.data);
      }
    },
    webSocketClose1() {
      console.log("websocket1断开连接");
    },

    initWebSocket2(url) {
      // console.log("url", url);
      this.wsuri2 = "ws://" + url + "/1_123456789";
      // this.wsuri2 = "ws://" + url + "/1_" + this.userMark;
      this.webSocket2 = new WebSocket(this.wsuri2);
      this.webSocket2.onmessage = this.webSocketOnMessage2;
      this.webSocket2.onopen = this.webSocketOnOpen2;
      this.webSocket2.onerror = this.webSocketOnError2;
      this.webSocket2.onclose = this.webSocketClose2;
    },
    webSocketOnOpen2() {
      console.log("websocket2已打开");
    },
    webSocketOnError2() {
      console.log("websocket2发生了错误");
    },
    webSocketOnMessage2(e) {
      if (!this.playFlag2) return;
      if (e.data) {
        const fileReader = new FileReader();
        fileReader.onload = () => {
          const arrayBuffer = fileReader.result; // 获取读取的 ArrayBuffer
          // 创建一个 DataView 来读取和解析 ArrayBuffer
          const dataView = new DataView(arrayBuffer);

          // 使用 DataView 的各种方法来读取数据
          // console.log('dataView', dataView)

          // 标识位
          // const int32Value = dataView.getInt32(0)
          // originStart
          const originStart = dataView.getFloat32(4);
          // originEnd
          const originEnd = dataView.getFloat32(8);
          // startFreq
          const startFreq = dataView.getFloat32(12);
          // endFreq
          const endFreq = dataView.getFloat32(16);
          // temprature
          const temprature = dataView.getFloat32(20);
          // dian
          const dian = dataView.getFloat32(24);
          // pointNum
          const pointNum = dataView.getInt32(28);
          // time
          const time = dataView.getInt32(32);
          // 数据类型
          const dataType = dataView.getInt16(36);
          // 长度
          const length = dataView.getInt16(38);
          // fFTAvg
          const fFTAvg = [];
          const fFTRealtime = [];
          const fFTMax = [];
          const fFTMin = [];
          for (let index = 40; index < 40 + 4 * length; index += 4) {
            fFTAvg.push(dataView.getFloat32(index));
            fFTRealtime.push(dataView.getFloat32(index));
          }

          switch (dataType) {
            case 3:
              for (
                let index = 40 + 4 * length;
                index < 40 + 8 * length;
                index += 4
              ) {
                fFTMax.push(dataView.getFloat32(index));
              }
              break;

            case 5:
              for (
                let index = 40 + 4 * length;
                index < 40 + 8 * length;
                index += 4
              ) {
                fFTMin.push(dataView.getFloat32(index));
              }
              break;
            case 7:
              for (
                let index = 40 + 4 * length;
                index < 40 + 8 * length;
                index += 4
              ) {
                fFTMax.push(dataView.getFloat32(index));
              }
              for (
                let index = 40 + 8 * length;
                index < 40 + 12 * length;
                index += 4
              ) {
                fFTMin.push(dataView.getFloat32(index));
              }
              break;

            default:
              break;
          }

          const data = {
            originStart,
            originEnd,
            startFreq,
            endFreq,
            temprature,
            dian,
            pointNum,
            time,
            dataType,
            length,
            fFTAvg,
            fFTRealtime,
            fFTMax,
            fFTMin,
            /* fFTMax: this.fFTMax,
            fFTMin: this.fFTMin */
          };
          // console.log('websocket接收数据:', data)
          try {
            // const data = JSON.parse(e.data)
            const chartObj = {};
            if (this.chartType2 === 1) {
              if (data.fFTRealtime) {
                // 绘制瀑布图的逻辑单独出
                chartObj.fFTRealtime = data.fFTRealtime;
              }

              if (
                this.$refs.chart13 &&
                data.fFTAvg &&
                this.$refs.chart13.detectType.includes("2")
              ) {
                chartObj.fFTAvg = data.fFTAvg;
              }
              if (
                this.$refs.chart13 &&
                data.fFTMax &&
                this.$refs.chart13.detectType.includes("3")
              ) {
                chartObj.fFTMax = data.fFTMax;
              }
              if (
                this.$refs.chart13 &&
                data.fFTMin &&
                this.$refs.chart13.detectType.includes("4")
              ) {
                chartObj.fFTMin = data.fFTMin;
              }

              if (Object.keys(chartObj).length) {
                this.$refs.chart13 &&
                  this.$refs.chart13.drawChart(
                    chartObj,
                    data.startFreq,
                    data.endFreq,
                    data.originStart,
                    data.originEnd
                  );
                this.$refs.chart14 &&
                  this.$refs.chart14.drawChart(
                    data.fFTRealtime,
                    data.startFreq,
                    data.endFreq,
                    data.originStart,
                    data.originEnd
                  );
              }

              if (data.save !== undefined) {
                this.$refs.realSetting2.saveForm.start =
                  data.save === false ? 0 : 1;
              }
            } else if (this.chartType2 === 0) {
              if (data.fFTRealtime) {
                // 绘制瀑布图的逻辑单独出
                chartObj.fFTRealtime = data.fFTRealtime;
              }

              if (
                this.$refs.chart13 &&
                data.fFTAvg &&
                this.$refs.chart13.detectType.includes("2")
              ) {
                chartObj.fFTAvg = data.fFTAvg;
              }
              if (
                this.$refs.chart13 &&
                data.fFTMax &&
                this.$refs.chart13.detectType.includes("3")
              ) {
                chartObj.fFTMax = data.fFTMax;
              }
              if (
                this.$refs.chart13 &&
                data.fFTMin &&
                this.$refs.chart13.detectType.includes("4")
              ) {
                chartObj.fFTMin = data.fFTMin;
              }

              if (Object.keys(chartObj).length) {
                this.$refs.chart13 &&
                  this.$refs.chart13.drawChart(
                    chartObj,
                    data.startFreq,
                    data.endFreq,
                    data.originStart,
                    data.originEnd
                  );
                this.$refs.chart14 &&
                  this.$refs.chart14.drawChart(
                    data.fFTRealtime,
                    data.startFreq,
                    data.endFreq,
                    data.originStart,
                    data.originEnd
                  );
              }
            }

            // 如果原始区间就小于1000，就不去做格式化数据的处理了
            if (
              this.$refs.chart13 &&
              data.originEnd - data.originStart > 1000
            ) {
              if (
                !this.$refs.chart13.disabledChange &&
                data.endFreq - data.startFreq < 1000 &&
                !this.$refs.chart13.formatStatus
              ) {
                this.$refs.chart13.formatStatus = true;
              } else if (
                data.endFreq - data.startFreq >= 1000 &&
                this.$refs.chart13.formatStatus
              ) {
                this.$refs.chart13.formatStatus = false;
              }
            }
          } catch (error) {
            console.log(error);
          }
        };
        fileReader.readAsArrayBuffer(e.data);
      }
    },
    webSocketClose2() {
      console.log("websocket2断开连接");
    },
    // 设备一参数配置/设备一切换工作模式
    async openDialog1(flag) {
      try {
        // 清空频谱图和瀑布图的内容
        this.$refs.chart11 && this.$refs.chart11.line.setData([]);
        this.$refs.chart11 &&
          this.$refs.chart11.line2 &&
          this.$refs.chart11.line2.setData([]);
        this.$refs.chart12 && this.$refs.chart12.series.clearData();
        if (this.chartType1 === 2) {
          // 文件回放模式 => 告诉后端用户不看实时和扫频了
          await this.getDeviceParams(this.deviceUrl[0], this.chartType1);
          this.getFilePlayback(this.deviceUrl[0]);
        } else {
          const {
            data: { data },
          } = await this.getDeviceParams(this.deviceUrl[0], this.chartType1);
          // console.log("设备1参数", data);
          // this.showDialog1 = true;
          await this.$nextTick();
          if (this.chartType1 === 0) {
            this.$refs.scanSetting1.scanForm.center = data.center / 1000;
            this.$refs.scanSetting1.scanForm.rbw = data.rbw;
            this.$refs.scanSetting1.scanForm.smooth = data.smooth;
            this.$refs.scanSetting1.scanForm.span = data.span / 1000;
            this.$refs.scanSetting1.scanForm.step = data.step;
            this.$refs.scanSetting1.scanForm.sweepTime = data.sweepTime;
            this.$refs.scanSetting1.scanForm.zengyi = data.zengyi;
            this.$refs.scanSetting1.scanForm.autoRbw = false;
            this.$refs.scanSetting1.deviceType = data.deviceType;
            this.$refs.scanSetting1.vbw = data.vbw;

            if (data.detectType) {
              const temArr = data.detectType.split(",");
              this.$refs.chart11.typeOptions.forEach((item) => {
                temArr.some((innerItem) => {
                  if (item.value === innerItem) {
                    item.isChoosed = true;
                    return true;
                  }
                });
              });
            }

            this.$refs.scanSetting1.scanUnit = {
              center: "MHz", // 中心频点单位
              span: "MHz", // 扫频宽度单位
              startFre: "MHz", // 起始频率单位
              stopFre: "MHz", // 终止频率单位
              rbw: "Hz", // 分辨率率单位
            };
            this.$refs.scanSetting1.changeFre();
          } else if (this.chartType1 === 1) {
            this.$refs.realSetting1.realtimeForm.bandwidth = data.bandwidth;
            this.$refs.realSetting1.realtimeForm.center = data.center / 1000;
            this.$refs.realSetting1.realtimeForm.rbw = data.rbw;
            this.$refs.realSetting1.realtimeForm.shepinPD = data.shepinPD;
            this.$refs.realSetting1.realtimeForm.smooth = data.smooth;
            this.$refs.realSetting1.realtimeForm.zengyi = data.zengyi;
            this.$refs.realSetting1.realtimeForm.outTrigger = data.outTrigger;
            this.$refs.realSetting1.deviceType = data.deviceType;

            if (data.detectType) {
              const temArr = data.detectType.split(",");
              // console.log('实时temArr', temArr)
              this.$refs.chart11.typeOptions.forEach((item) => {
                temArr.some((innerItem) => {
                  if (item.value === innerItem) {
                    item.isChoosed = true;
                    return true;
                  }
                });
              });
            }

            this.$refs.realSetting1.realUnit = {
              center: "MHz", // 中心频点单位
              bandwidth: "MHz", // 中频带宽单位
              rbw: "Hz", // 分辨率单位
              sample: "Hz", // 采样率单位
            };
          }
          this.changeLine1(this.chartType1);
        }
        if (flag === true) return;
        this.confirm1("noClose");
      } catch (error) {
        console.log(error);
      }
    },
    // 设备二参数配置/设备二切换工作模式
    async openDialog2(flag) {
      try {
        const {
          data: { data },
        } = await this.getDeviceParams(this.deviceUrl[1], this.chartType2);
        // console.log("设备2参数", data);
        // this.showDialog2 = true;
        await this.$nextTick();
        if (this.chartType2 === 0) {
          this.$refs.scanSetting2.scanForm.center = data.center / 1000;
          this.$refs.scanSetting2.scanForm.rbw = data.rbw;
          this.$refs.scanSetting2.scanForm.smooth = data.smooth;
          this.$refs.scanSetting2.scanForm.span = data.span / 1000;
          this.$refs.scanSetting2.scanForm.step = data.step;
          this.$refs.scanSetting2.scanForm.sweepTime = data.sweepTime;
          this.$refs.scanSetting2.scanForm.zengyi = data.zengyi;
          this.$refs.scanSetting2.scanForm.autoRbw = false;
          this.$refs.scanSetting2.deviceType = data.deviceType;
          this.$refs.scanSetting2.vbw = data.vbw;

          if (data.detectType) {
            const temArr = data.detectType.split(",");
            // console.log('实时temArr', temArr)
            this.$refs.chart13.typeOptions.forEach((item) => {
              temArr.some((innerItem) => {
                if (item.value === innerItem) {
                  item.isChoosed = true;
                  return true;
                }
              });
            });
          }

          this.$refs.scanSetting2.scanUnit = {
            center: "MHz", // 中心频点单位
            span: "MHz", // 扫频宽度单位
            startFre: "MHz", // 起始频率单位
            stopFre: "MHz", // 终止频率单位
            rbw: "Hz", // 分辨率率单位
          };
          this.$refs.scanSetting2.changeFre();
        } else if (this.chartType2 === 1) {
          this.$refs.realSetting2.realtimeForm.bandwidth = data.bandwidth;
          this.$refs.realSetting2.realtimeForm.center = data.center / 1000;
          this.$refs.realSetting2.realtimeForm.rbw = data.rbw;
          this.$refs.realSetting2.realtimeForm.shepinPD = data.shepinPD;
          this.$refs.realSetting2.realtimeForm.smooth = data.smooth;
          this.$refs.realSetting2.realtimeForm.zengyi = data.zengyi;
          this.$refs.realSetting2.realtimeForm.outTrigger = data.outTrigger;
          this.$refs.realSetting2.deviceType = data.deviceType;

          if (data.detectType) {
            const temArr = data.detectType.split(",");
            // console.log('实时temArr', temArr)
            this.$refs.chart13.typeOptions.forEach((item) => {
              temArr.some((innerItem) => {
                if (item.value === innerItem) {
                  item.isChoosed = true;
                  return true;
                }
              });
            });
          }

          this.$refs.realSetting2.realUnit = {
            center: "MHz", // 中心频点单位
            bandwidth: "MHz", // 中频带宽单位
            rbw: "Hz", // 分辨率单位
            sample: "Hz", // 采样率单位
          };
        }
        this.changeLine2(this.chartType2);
        if (flag === true) return;
        this.confirm2("noClose");
      } catch (error) {
        console.log(error);
      }
    },

    // 修改了参考电平，重新设置y轴区间
    changeYRange1(max, min) {
      this.$refs.chart11.series.setMaxYInterval([min, max]);
      this.$refs.chart12.series.setValueInterval(min, max);
    },
    // 修改了参考电平，重新设置y轴区间
    changeYRange2(max, min) {
      this.$refs.chart13 &&
        this.$refs.chart13.series.setMaxYInterval([min, max]);
      this.$refs.chart14 &&
        this.$refs.chart14.series.setValueInterval(min, max);
    },

    // 获取设备参数
    getDeviceParams(url, params) {
      return axios({
        url: "http://" + url + "/interface/param/get/" + params,
        method: "get",
      });
    },

    // 获取设备工作模式
    getWorkMode(url) {
      return axios({
        url: "http://" + url + "/interface/workMode/query",
        method: "get",
      });
    },
    // 设备一参数配置
    async confirm1(flag) {
      if (this.chartType1 === 0) {
        try {
          this.loading1 = true;
          await this.$refs.scanSetting1.sweepConfig(this.deviceUrl[0]);
          await this.$refs.scanSetting1.changeVbw(this.deviceUrl[0]);
          if (flag === "noClose") return;
          this.$message.success("配置成功！");
          this.showDialog1 = false;
        } catch (error) {
          this.$message.error("操作失败！");
        } finally {
          this.loading1 = false;
        }
      } else if (this.chartType1 === 1) {
        try {
          this.loading1 = true;
          await this.$refs.realSetting1.realTimeConfig(this.deviceUrl[0], flag);
          if (flag === "noClose") return;
          this.$message.success("配置成功！");
          this.showDialog1 = false;
        } catch (error) {
          this.$message.error("操作失败！");
        } finally {
          this.loading1 = false;
        }
      }
    },
    // 设备二参数配置
    async confirm2(flag) {
      if (this.chartType2 === 0) {
        try {
          this.loading2 = true;
          await this.$refs.scanSetting2.sweepConfig(this.deviceUrl[1]);
          await this.$refs.scanSetting2.changeVbw(this.deviceUrl[1]);
          if (flag === "noClose") return;
          this.$message.success("配置成功！");
          this.showDialog2 = false;
        } catch (error) {
          this.$message.error("操作失败！");
        } finally {
          this.loading2 = false;
        }
      } else if (this.chartType2 === 1) {
        try {
          this.loading2 = true;
          await this.$refs.realSetting2.realTimeConfig(this.deviceUrl[1], flag);
          if (flag === "noClose") return;
          this.$message.success("配置成功！");
          this.showDialog2 = false;
        } catch (error) {
          this.$message.error("操作失败！");
        } finally {
          this.loading2 = false;
        }
      }
    },
    showLine(line, bool) {
      this.$refs.chart11[line].setVisible(bool);
    },
    showLine2(line, bool) {
      this.$refs.chart13[line].setVisible(bool);
    },

    // 获取设备里的历史文件和当前回放状态
    async getFilePlayback(url) {
      await this.$nextTick();
      try {
        const {
          data: { data },
        } = await this.getFileListAPI(url, "");
        this.fileList = data;

        const {
          data: { data: data1 },
        } = await this.getPlaybackStatusAPI(url);
        this.playbackStatus = data1.start;

        // console.log('文件列表:', data, '文件回放状态', data1)
      } catch (error) {
        console.log(error);
      }
    },
    // 获取设备里的历史文件的接口
    getFileListAPI(url, params) {
      return axios({
        url: "http://" + url + "/playback/get/files/" + params,
        method: "get",
      });
    },

    // 查询当前文件回放的状态的接口
    getPlaybackStatusAPI(url, params) {
      return axios({
        url: "http://" + url + "/playback/status",
        method: "get",
        params,
      });
    },
    // 开始回放
    async startPlay() {
      if (!this.fileName)
        return this.$message.warning("请选择想要回放的文件！");
      try {
        await this.startPlayAPI(this.deviceUrl[0], {
          fileName: this.fileName,
        });
        this.playbackStatus = true;
        this.$message.success("开始回放成功！");
      } catch (error) {
        console.log(error);
        this.$message.error("操作失败！");
      }
    },
    // 停止回放
    async stopPlay() {
      try {
        await this.stopPlayAPI(this.deviceUrl[0]);
        this.playbackStatus = false;
        this.$message.success("停止回放成功！");
      } catch (error) {
        console.log(error);
        this.$message.error("操作失败！");
      }
    },

    // 文件回放开始
    startPlayAPI(url, data) {
      return axios({
        url: "http://" + url + "/playback/start",
        method: "post",
        data,
      });
    },
    // 文件停止回放
    stopPlayAPI(url, params) {
      return axios({
        url: "http://" + url + "/playback/stop",
        method: "get",
        params,
      });
    },

    changeLine1(newVal) {
      this.$nextTick(() => {
        if (newVal === 0) {
          // 扫频模式
          if (!this.$refs.chart11.detectType.includes("2")) {
            this.showLine("line", false);
          } else {
            this.showLine("line", true);
          }
          if (!this.$refs.chart11.detectType.includes("3")) {
            this.showLine("line2", false);
          } else {
            this.showLine("line2", true);
          }
          if (!this.$refs.chart11.detectType.includes("4")) {
            this.showLine("line3", false);
          } else {
            this.showLine("line3", true);
          }
        } else if (newVal === 1) {
          // 实时模式
          if (!this.$refs.chart11.detectType.includes("2")) {
            this.showLine("line", false);
          } else {
            this.showLine("line", true);
          }
          if (!this.$refs.chart11.detectType.includes("3")) {
            this.showLine("line2", false);
          } else {
            this.showLine("line2", true);
          }
          if (!this.$refs.chart11.detectType.includes("4")) {
            this.showLine("line3", false);
          } else {
            this.showLine("line3", true);
          }
        }
      });
    },

    changeLine2(newVal) {
      this.$nextTick(() => {
        if (newVal === 0) {
          // 扫频模式
          if (!this.$refs.chart13.detectType.includes("2")) {
            this.showLine2("line", false);
          } else {
            this.showLine2("line", true);
          }
          if (!this.$refs.chart13.detectType.includes("3")) {
            this.showLine2("line2", false);
          } else {
            this.showLine2("line2", true);
          }
          if (!this.$refs.chart13.detectType.includes("4")) {
            this.showLine2("line3", false);
          } else {
            this.showLine2("line3", true);
          }
        } else if (newVal === 1) {
          // 实时模式
          if (!this.$refs.chart13.detectType.includes("2")) {
            this.showLine2("line", false);
          } else {
            this.showLine2("line", true);
          }
          if (!this.$refs.chart13.detectType.includes("3")) {
            this.showLine2("line2", false);
          } else {
            this.showLine2("line2", true);
          }
          if (!this.$refs.chart13.detectType.includes("4")) {
            this.showLine2("line3", false);
          } else {
            this.showLine2("line3", true);
          }
        }
      });
    },
    changePlayFlag1(val) {
      this.playFlag1 = val;
    },
    changePlayFlag2(val) {
      this.playFlag2 = val;
    },
    changeCenterFre1(startFre, stopFre) {
      this.$refs.scanSetting1.scanForm.startFre = startFre;
      this.$refs.scanSetting1.scanForm.stopFre = stopFre;
      this.$refs.scanSetting1.changeCenterFre(true);
    },
    changeCenterFre2(startFre, stopFre) {
      this.$refs.scanSetting2.scanForm.startFre = startFre;
      this.$refs.scanSetting2.scanForm.stopFre = stopFre;
      this.$refs.scanSetting2.changeCenterFre(true);
    },
  },
};
</script>

<style lang="scss" scoped>
.chartsContainer {
  margin: 20px 0 0;
  width: 100%;
  background-color: #f9f8fd;

  .title {
    height: 32px;
    line-height: 32px;
    font-size: 16px;
    font-weight: bold;
    padding: 0 10px;
  }

  .setting {
    margin: 0px 15px;
    width: calc(100% - 30px);
    height: 32px;
    line-height: 32px;
    display: flex;

    .label {
      font-size: 14px;
      margin-left: 20px;

      &:first-child {
        margin-left: 0;
      }
    }

    /deep/ .el-select__tags {
      flex-wrap: nowrap;
      overflow: hidden;
    }
  }

  .charts {
    margin: 10px 15px;
    width: calc(100% - 30px);

    .chart1 {
      margin-bottom: 8px;
      box-sizing: border-box;
      position: relative;
      .top {
        display: flex;
        height: 32px;
        line-height: 32px;

        .chartTitle {
          font-size: 14px;
          padding-left: 5px;
        }

        /deep/ .el-button--mini {
          padding: 5px;
          height: 28px;
          position: relative;
          top: 3px;
          margin-left: 20px;
        }

        /deep/ .el-input--small .el-input__inner {
          height: 28px;
          line-height: 28px;
        }
      }
    }
  }
  .settingForm {
    display: flex;
    flex-wrap: wrap;
  }
}
</style>
